/*
 * @lc app=leetcode.cn id=2429 lang=golang
 *
 * [2429] 最小 XOR
 */
package Solutions

// @lc code=start
func minimizeXor(num1 int, num2 int) int {
	oneCount2 := 0
	for num2 != 0 {
		if num2&1 == 1 {
			oneCount2++
		}
		num2 >>= 1
	}
	oneCount1 := 0
	num1T := num1
	for num1T != 0 {
		if num1T&1 == 1 {
			oneCount1++
		}
		num1T >>= 1
	}
	dif := oneCount1 - oneCount2
	if dif > 0 {
		mask := 1<<63 - 1
		i := 0
		for ; dif > 0; i++ {
			if num1&(1<<i) != 0 {
				dif--
			}
			mask >>= 1
		}
		mask <<= i
		return num1 & mask
	} else if dif == 0 {
		return num1
	} else {
		ans := 0
		i := 0
		for ; dif < 0; i++ {
			if num1&1 == 0 {
				dif++
			}
			ans += 1 << i
			num1 >>= 1

		}
		num1 <<= i
		return ans | num1
	}

}

// @lc code=end
